<template>
    <div class="freight_setting_container">
        <el-form label-width="0px">
            <el-form-item style="margin-bottom: 0;">
                <span>计费算法：1）根据物品重量查找对应的计费规则，具体：a、物品重量处于某个规则的起始重量、终止重量之间，则直接匹配该规则；
                    b、物品重量大于A规则的终止重量而小于B规则的起始重量时，则与B规则匹配；
                    c、物品重量大于所有规则的终止重量，则与最大终止重量的规则匹配；<br/>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2）计费重量=(物品重量+包材重量)/包材系数，计费重量采用向上取整</span>
            </el-form-item>
            <el-form-item>
                <span>计算运费：A）按单价，运费=计费重量*单价；B）固定运费，运费=固定运费；C）查费率表，计费重量按重量梯度进行规范化，得到费率表内重量，再查费率表得到对应重量的运费</span>
            </el-form-item>
            <el-form-item>
                <el-input style="width: 130px;" placeholder="物品重量(kg)"
                          v-double-input-new="{len: 2, negative: false}" v-model="test_weight" />
                <el-button @click="testCalc()">试算运费</el-button>
                <span style="margin-left: 10px;">{{ testResult }}</span>
            </el-form-item>
            <el-form-item>
                <el-tabs v-model="activeName" type="border-card">
                    <el-tab-pane label="计费规则" name="rule">
                        <vxe-table-template ref="itemTable" :data="itemList" :options.sync="itemTableOptions" />
                    </el-tab-pane>
                    <el-tab-pane label="运费费率表" name="rate">
                        <div class="btn_area" v-if="!propsData.detail">
                            <el-button type="primary" @click="openBatchDialog()">批量设置</el-button>
                        </div>
                        <vxe-table-template ref="rateTable" :data="rateList" :options.sync="rateTableOptions" />
                    </el-tab-pane>
                </el-tabs>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import freightUtils from "../../freightUtils";

export default {
    name: "FreightSetting",
    props: {
        propsData: {
            type: Object,
            default() {
                return {
                    init: true,
                };
            },
        },
    },
    data() {
        let _this = this;
        return {
            test_weight: 0,
            testResult: '',
            activeName: "rule",
            rateList: [],
            baseRateRow: {},
            rateTableOptions: {
                ref: "freightRateTable",
                edit: true,
                columns: [
                    {
                        label: "重量(kg)",
                        prop: "weight",
                        align: "center",
                        editRender: {
                            name: "ElInput",
                            double: 2,
                            events: { input: _this.rewriteChangeRow },
                        },
                    },
                    {
                        label: "运费",
                        prop: "freight",
                        align: "center",
                        editRender: {
                            name: "ElInput",
                            double: 2,
                            events: { input: _this.rewriteChangeRow },
                        },
                    },
                ],
                operates: {
                    width: 80,
                    list: [
                        {
                            id: "add",
                            icon: "fa fa-plus",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "添加",
                            },
                            method: (index, row) => {
                                _this.rateList = _this.addRow(_this.rateList, _this.baseRateRow, row);
                            },
                        },
                        {
                            id: "info",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "删除",
                            },
                            method: (index, row) => {
                                _this.rateList = _this.delRow(_this.rateList, row, _this.baseRateRow);
                            },
                        },
                    ],
                },
                getMaxHeight() {
                    let height = $(_this.getActiveTabsContainer()).height();
                    return height * 0.8 - 250;
                },
            },
            itemList: [],
            baseItemRow: {},
            itemTableOptions: {
                ref: "freightItemTable",
                edit: true,
                columns: [
                    {
                        label: "起始重量\n(kg)",
                        prop: "min_value",
                        align: "center",
                        editRender: {
                            name: "ElInput",
                            double: 2,
                            events: { input: _this.rewriteChangeRow },
                        },
                    },
                    {
                        label: "截止重量\n(kg)",
                        prop: "max_value",
                        align: "center",
                        editRender: {
                            name: "ElInput",
                            double: 2,
                            events: { input: _this.rewriteChangeRow },
                        },
                    },
                    {
                        label: "包材重量\n(kg)",
                        prop: "package_weight",
                        align: "center",
                        editRender: {
                            name: "ElInput",
                            double: 2,
                            events: { input: _this.rewriteChangeRow },
                        },
                    },
                    {
                        label: "包材系数",
                        prop: "package_ratio",
                        align: "center",
                        editRender: {
                            name: "ElInput",
                            double: 2,
                            events: { input: _this.rewriteChangeRow },
                        },
                    },
                    {
                        label: "重量梯度\n(kg)",
                        prop: "weight_grad",
                        align: "center",
                        editRender: {
                            name: "ElInput",
                            double: 2,
                            events: { input: _this.rewriteChangeRow },
                        },
                    },
                    {
                        label: "计价模式",
                        prop: "valuation_mode",
                        align: "center",
                        editRender: {
                            name: "ElSelect",
                            autofocus: 'input.el-input__inner',
                            props: {
                                filterable: true,
                            },
                            options: [
                                { label: "查费率表", value: "rate" },
                                { label: "固定运费", value: "freight" },
                                { label: "固定单价", value: "price" },
                            ],
                            events: { change: _this.rewriteChangeRow },
                        },
                    },
                    {
                        label: "固定运费",
                        prop: "freight",
                        align: "center",
                        editRender: {
                            name: "ElInput",
                            double: 2,
                            events: { input: _this.rewriteChangeRow },
                        },
                    },
                    {
                        label: "运费单价",
                        prop: "price",
                        align: "center",
                        editRender: {
                            name: "ElInput",
                            double: 2,
                            events: { input: _this.rewriteChangeRow },
                        },
                    },
                ],
                operates: {
                    list: [
                        {
                            id: "add",
                            icon: "fa fa-plus",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "添加",
                            },
                            method: (index, row) => {
                                _this.itemList = _this.addRow(_this.itemList, _this.baseItemRow, row);
                            },
                        },
                        {
                            id: "info",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "删除",
                            },
                            method: (index, row) => {
                                _this.itemList = _this.delRow(_this.itemList, row, _this.baseItemRow);
                            },
                        },
                    ],
                },
                getMaxHeight() {
                    let height = $(_this.getActiveTabsContainer()).height();
                    return height * 0.8 - 250;
                },
            },
        };
    },
    watch: {
        propsData: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        init() {
            const _this = this;
            if (_this.propsData.init) {
                return;
            }
            _this.activeName = "rule";
            _this.rateList = [];
            _this.itemList = [];
            _this.initRateData(_this.propsData.row);
            _this.initItemData(_this.propsData.row);
            _this.rateTableOptions = $.extend({}, _this.rateTableOptions, {
                edit: !_this.propsData.detail,
                operates: _this.propsData.detail ? {} : _this.rateTableOptions.operates,
            });
            _this.itemTableOptions = $.extend({}, _this.itemTableOptions, {
                edit: !_this.propsData.detail,
                operates: _this.propsData.detail ? {} : _this.itemTableOptions.operates,
            });
        },
        rewriteChangeRow({ $rowIndex, data, row, column }) {
            let $this = this;
            column = Object.assign({}, column, column.params);
            // 手动限制控制数字位数
            if (column.editRender && column.editRender.double) {
                $this.$set(
                    row,
                    column.prop,
                    $this.$XEUtils.DoubleInput(row[column.prop], column.editRender.double)
                );
                return;
            }
            if (column.editRender) {
                $this.$set(row, column.prop, row[column.prop]);
            }
        },
        addRow(dataList, baseRow, row) {
            let _this = this;
            let list = dataList.map((item) => $.extend({}, baseRow, item));
            if (row) {
                list.splice(row._index + 1, 0, { ...baseRow });
            } else list.push({});
            return _this.resetIndex(list, '_index', baseRow);
        },
        delRow(dataList, row, baseRow) {
            let _this = this;
            let list = dataList
            .map((item) => $.extend({}, item))
            .filter((item) => row._index !== item._index);
            if (!_this.$utils.isNotEmptyList(list)) {
                list = [ {} ];
            }
            return _this.resetIndex(list, '_index', baseRow);
        },
        initRateData(row) {
            let _this = this;
            let rateList = row.rate_list;
            let baseRow = {}
            _this.rateTableOptions.columns.map(item => {
                baseRow[item.prop] = null
            })
            this.baseRateRow = baseRow
            if (!_this.$utils.isNotEmptyList(rateList)) {
                rateList = [ { ...baseRow } ];
            }
            _this.rateList = _this.resetIndex(rateList, '_index', baseRow);
        },
        initItemData(row) {
            let _this = this;
            let itemList = row.item_list;
            let baseRow = {}
            _this.itemTableOptions.columns.map(item => {
                baseRow[item.prop] = null
            })
            this.baseItemRow = baseRow
            if (!_this.$utils.isNotEmptyList(itemList)) {
                itemList = [ { ...baseRow } ];
            }
            _this.itemList = _this.resetIndex(itemList, '_index', baseRow);
        },
        getSubData() {
            let _this = this;
            let subData = {
                id: _this.propsData.row.id,
                sid: _this.propsData.row.sid,
            };
            subData.rate_list = _this.rateList.map((item, index) => {
                let obj = $.extend({}, item);
                obj.sn = index + 1;
                return obj;
            });
            subData.item_list = _this.itemList.map((item, index) => {
                let obj = $.extend({}, item);
                obj.sn = index + 1;
                return obj;
            });
            return subData;
        },
        testCalc() {
            let subData = this.getSubData();
            let fr = freightUtils.calcFreight(this.test_weight, subData);
            this.testResult = fr + "元"
        },
        openBatchDialog() {
            this.$emit('event', {
                type: 'openBatchDialog',
                data: {
                    rateList: this.rateList,
                },
            });
        },
        updateRateList(rateList) {
            this.rateList = rateList;
        },
        async confirm() {
            const _this = this;
            let subData = _this.getSubData();
            return _this.fetchData(_this.$api.API_SaveBaseExpressOrg, subData).then(() => {
                _this.$message.success('设置成功！');
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
};
</script>

<style lang="less" rel="stylesheet/less" scoped>
.freight_setting_container {
    width: 100%;
    height: 100%;
    overflow: hidden;

    /deep/ .el-tabs__content {
        padding: 10px;

        .el-tab-pane {
            .btn_area {
                margin-bottom: 10px;
            }
        }
    }
}
</style>
